<template>
  <div id="common" v-show="common">
    <svg class="icon icon-erweima" aria-hidden="true" @click="wechats">
        <use xlink:href="#icon-erweimajiaobiao"></use>
    </svg>
    <h1 style="text-align: center">千锋管理系统</h1>
    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="demo-loginForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          type="text"
          v-model="loginForm.username"
          autocomplete="off"
        ></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="loginForm.password"
          autocomplete="off"
        ></el-input>
      </el-form-item>

      <el-form-item label="验证码" prop="captcha">
        <el-input v-model.number="loginForm.captcha" type="text" class="code">
        </el-input>
        <!-- 点击获取验证码 -->
        <span @click="updateCaptcha" id="updateCode" v-html="captchaSvg" v-loading="loading"></span>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('loginForm')"
          >提交</el-button
        >

      </el-form-item>
    </el-form>
    
    <!-- 跳转短信登陆 -->
    <div class="change" @click="switchs">
        <svg class="icon icon-iphone" aria-hidden="true">
            <use xlink:href="#icon-iphone"></use>
        </svg>
      <a href="javascript:;">切换短信登录</a>
    </div>

  </div>
</template>


<script>
//引入api的方法
import * as api from "@/api/users"
import storage from "../../utils/storage"

//映射vuex
// import { mapMutations } from "vuex"



//校验验证码
var validateCaptcha = (rule, value, callback) => {
  if (value) {
    callback();
  } else {
    callback("验证码必须是5位");
  }
};
//检验用户名
var validateUsername = (rule, value, callback) => {
  // console.log(rule);
  // console.log(value);
  var uPattern = /^[a-zA-Z0-9_-]{3,16}$/;
  if (uPattern.test(value)) {
    callback();
  } else {
    callback("账号3-16字母数字下划线");
  }
};
//校验密码
var validatePassword = (rule, value, callback) => {
  // var pPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{3,}$/
  // var pPattern = /^(?=.*\d)[A-Za-z\d]{3,}$/;
  // var pPattern = /^(?=.*\d){3,}$/;
  if (value) {
    callback();
  } else {
    callback("密码至少3个字符");
  }
};
export default {
    props:['common','wechat'],
    // props:['common'],
    data() {
        return {
        captchaSvg:"",//验证码Svg
        loading:false,
        
        loginForm: {
            username: "",
            password: "",
            captcha: "",   

        },
        //表单验证规则
        rules: {
            username: [{ validator: validateUsername, trigger: "blur" }],
            password: [{ validator: validatePassword, trigger: "blur" }],
            captcha: [{ validator: validateCaptcha, trigger: "blur" }],
        },
    };
  },
  mounted () {
    // this.updateCode()
  },
  created () {
    this.updateCaptcha()
  },
  methods: {
    //映射vuex的mutations
    // ...mapMutations(['users/SET_USERINFO']),



    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //校验通过  
          // alert("submit!");
          // console.log(this.loginForm.captcha);
          api.verifyCaptcha(this.loginForm.captcha)
          .then(async res => {
            // console.log(res);
           
            if(res.data.state){
              //验证码通过，校验用户名和密码
              let {username,password} = this.loginForm
              let res = await api.loginApi(username,password)
              // console.log(res);
              // let{state:userInfo} = res.data
              //登入成功
              if(res.data.state){
                //存储用户信息到本地
                this.storageUserInfo(res.data)

                //跳转到主页 
                this.$router.push("/welcome")
                // console.log(1);
              }
            }else{
              //验证码不通过  刷新验证码
              this.updateCaptcha()
            }
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //封装一个方法 用于存储用户的信息和token
    storageUserInfo({ userInfo, token, permission }){
      //将信息存储到vuex
      this.$store.commit('users/SET_USERINFO',userInfo)
      storage.set('userInfo',userInfo )
      storage.set('sasa-token', token)
			storage.set('permission', permission)
      // let r = storage.get('userInfo')
      // console.log(r);
    },
  
    



    //跳转到短信登陆
    switchs(){
        this.$emit('switchs')
    },
    //跳转到二维码登录
    wechats(){
        this.$emit('wechats')
    },

    //封装一个方法，获取验证码
    // updateCaptcha(){
    //     //获取刷新验证码
    //     fetch("http://www.chst.vip/users/refreshCaptcha")
    //     .then(body => body.json())
    //     .then(res => {
    //         document.getElementById('updateCode').innerHTML = ''
    //         document.getElementById('updateCode').innerHTML = res.img
    //     })

    // },
    // //获取验证码
    // updateCode(){
    //     fetch("http://www.chst.vip/users/getCaptcha?v=next")
    //     .then(body => body.json())
    //     .then(res => {
    //         // console.log(res);
    //         // console.log(res.img);
    //         document.getElementById('updateCode').innerHTML = res.img

    //     })
    // },


    //获取验证码
    updateCaptcha(){
      //打开加载动画
      this.loading = true
      api.getCaptcha().then((res) => {
        console.log(res);
        // let {img} = res.data;
        // this.captchaSvg = img;
        this.captchaSvg = res.data.img;
        //关掉加载动画
        this.loading = false
      })
    }



  },
};
</script>


<style scoped lang="less">
h1 {
  margin: 0 0 60px 0;
  text-align: center;
  color: #000;
}
.el-input {
  position: relative;
  font-size: 14px;
  width: 250px;
}

.el-input {
  /deep/ .el-input__inner {
    width: 100%;
  }
}
/deep/ .el-form-item__label {
  color: #333;
}

.el-form-item__content {
  span {
    display: inline-block;
    width: 150px;
    height: 44px;
    background-color: white;
    cursor: pointer;
    border: 0;
    border-radius: 0 5px 5px 0;
    position: absolute;
    // top: 1px;
  }
}

/deep/ .code{
    width: 100px;
}
/deep/ .code .el-input__inner{
    border-radius:  5px 0 0 5px ;
    border:0;
    height: 44px;
}

.el-button {
  background: linear-gradient(90deg, #cbd0e1, #bfc1d8);
  width: 250px;
  color: #333;
}
/deep/.el-button--primary {
  border-color: #c8c8dc;
}
/deep/ .change {
  margin-left: 100px;
  width: 250px;
  text-align: center;
}
a {
  color: #666;
}
.icon-erweima{
    position: absolute;
    right:10px;
    top:10px;
    font-size:60px!important;
    color: #bfc3d2!important;
}
.icon-iphone{
    font-size:18px!important;
}
</style>